package com.sunwayworld.basemodule.business.prefolder.io;

import com.sunwayworld.baseline.framework.override.LimsExcelHelper;
import com.sunwayworld.basemodule.business.operationbatch.bean.LimsPreTaskSupplementBean;
import com.sunwayworld.basemodule.business.operationbatch.service.LimsPreTaskSupplementService;
import com.sunwayworld.basemodule.business.prefolder.bean.LimsPreFolderBean;
import com.sunwayworld.basemodule.business.prefolder.service.LimsPreFolderService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.exception.InvalidDataException;
import com.sunwayworld.framework.io.file.FilePathDTO;
import com.sunwayworld.framework.io.file.FilePathManager;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.ServletUtils;
import com.sunwayworld.framework.utils.StringUtils;
import com.sunwayworld.module.item.file.bean.CoreFileBean;
import com.sunwayworld.module.item.file.bean.CoreFileImportResultDTO;
import com.sunwayworld.module.item.file.function.CoreFileImportFunction;
import com.sunwayworld.module.item.file.manager.CoreFileManager;
import com.sunwayworld.module.item.file.utils.CoreFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component(value = "LimsPreTaskSupplementImportFileFunction")
@GikamBean
public class LimsPreTaskSupplementImportFileFunction implements CoreFileImportFunction {

    @Autowired
    @Lazy
    private LimsPreFolderService limsPreFolderService;

    @Lazy
    @Autowired
    private LimsPreTaskSupplementService preTaskSupplementService;

    @Override
    @Transactional
    public CoreFileImportResultDTO apply(CoreFileBean coreFileBean) {
        CoreFileImportResultDTO resultDTO = new CoreFileImportResultDTO();
        FilePathDTO fr = CoreFileUtils.toFilePath(coreFileBean);

        // 从tos服务器下载
        CoreFileManager coreFileManager = ApplicationContextHelper.getBean(CoreFileManager.class);
        coreFileManager.download(coreFileBean, FilePathManager.getLocalPath(fr));

        String operationBatch = ServletUtils.getCurrentRequest().getParameter("operationBatch");
        List<LimsPreFolderBean> itemList = LimsExcelHelper.readDataFromExcel(FilePathManager.getLocalPath(fr).toString(), 0, 1, LimsPreFolderBean.class);
        if (itemList.isEmpty() && !StringUtils.isBlank(operationBatch)) {
            throw new InvalidDataException("数据存在异常，请检查！");
        }
        List<LimsPreFolderBean> existsPrefolders = limsPreFolderService.selectListByFilter(SearchFilter.instance().match("operationBatch", operationBatch).filter(MatchPattern.EQ));
        itemList.stream().filter(Objects::nonNull).forEach(i -> {
            if (i.getId() == null || existsPrefolders.stream().noneMatch(ef -> ef.getId().equals(i.getId()))) {
                if (!StringUtils.isBlank(i.getExt$Item("validateimpmsg"))) {
                    i.setExt$Item("validateimpmsg", i.getExt$Item("validateimpmsg").concat("不存在此下发批次！"));
                } else {
                    i.setExt$Item("validateimpmsg", "不存在此下发批次！");
                }
            }
        });
        // 返还校验结果
        if (itemList.stream().anyMatch(i -> !StringUtils.isEmpty(i.getExt$Item("validateimpmsg")))) {
            FilePathDTO filePathDTO = LimsExcelHelper.writeImportFailureListAsExcel(FilePathManager.getLocalPath(fr).toString(), itemList, 0, 1, "导入错误信息.xlsx", false);
            resultDTO.setUrl(FilePathManager.getUrl(filePathDTO));
            resultDTO.setMessage("导入失败");
            return resultDTO;
        }
        // 获取批次补充信息
        List<LimsPreTaskSupplementBean> preTaskSupplementBeanList = preTaskSupplementService.selectListByFilter(SearchFilter.instance()
                .match("preFolderId", existsPrefolders.stream().map(LimsPreFolderBean::getId).collect(Collectors.toList())).filter(MatchPattern.OR));

        List<LimsPreTaskSupplementBean> update = new ArrayList<>();
        existsPrefolders.forEach(e -> {
            itemList.stream().filter(i -> i.getId() != null && i.getId().equals(e.getId())).findAny().ifPresent(i -> {
                List<LimsPreTaskSupplementBean> supplementBeans = preTaskSupplementBeanList.stream().filter(s -> s.getPreFolderId().equals(e.getId())).collect(Collectors.toList());
                supplementBeans.forEach(sb -> {
                    i.getExt$().keySet().stream().filter(key -> key.equalsIgnoreCase(sb.getFieldName())).findAny().ifPresent(key -> {
                        sb.setFieldValue(i.getExt$Item(key));
                        update.add(sb);
                    });
                });
                e.setExperimentNo(i.getExperimentNo());
            });
        });
        if (!update.isEmpty()) {
            preTaskSupplementService.getDao().fastUpdate(update, "fieldValue");
        }
        limsPreFolderService.getDao().fastUpdate(existsPrefolders, "experimentNo");
        resultDTO.setMessage("导入成功");
        return resultDTO;
    }

    @Override
    public boolean test(CoreFileBean coreFile, String service) {
        return true;
    }
}
